package org.lzy.shop.database.util

import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.Date

class Converters {
    // 使用伴生对象创建Gson实例，确保线程安全
    companion object {
        private val gson = Gson()
    }

    // 为List<String>提供专用转换器，避免使用可空类型
    @TypeConverter
    fun fromStringList(value: List<String>?): String? {
        if (value == null) {
            return null
        }
        try {
            return gson.toJson(value)
        } catch (e: Exception) {
            return null
        }
    }

    // 为MutableList<String?>?提供专用转换器
    @TypeConverter
    fun fromMutableListString(value: MutableList<String?>?): String? {
        if (value == null) {
            return null
        }
        try {
            return gson.toJson(value)
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    // 添加缺失的逆向转换方法
    @TypeConverter
    fun toMutableListString(value: String?): MutableList<String?>? {
        if (value == null) {
            return null
        }
        try {
            val type = object : TypeToken<MutableList<String?>?>() {}.type
            return gson.fromJson(value, type)
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }


    @TypeConverter
    fun toStringList(value: String?): List<String>? {
        if (value == null) {
            return null
        }
        try {
            val type = object : TypeToken<List<String>>() {}.type
            return gson.fromJson(value, type)
        } catch (e: Exception) {
            return null
        }
    }

    @TypeConverter
    fun fromTimestamp(value: Long?): Date? {
        return value?.let { Date(it) }
    }

    @TypeConverter
    fun dateToTimestamp(date: Date?): Long? {
        return date?.time
    }
}